﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class RateControlHelper
    {
        // Fields
        private int _MaxSleepMsec;
        private int _MinSleepMsec;
        private int _SleepMsec;
        private int _SleepStep;

        // Methods
        public RateControlHelper()
        {
            this._SleepMsec = 0x3e8;
            this._MaxSleepMsec = 0x1d4c0;
            this._MinSleepMsec = 0x3e8;
            this._SleepStep = 0x2710;
        }

        public RateControlHelper(int SleepStep)
        {
            this._SleepMsec = 0x3e8;
            this._MaxSleepMsec = 0x1d4c0;
            this._MinSleepMsec = 0x3e8;
            this._SleepStep = 0x2710;
            this._SleepStep = SleepStep;
        }

        public RateControlHelper(int MaxSleepMsec, int MinSleepMsec)
        {
            this._SleepMsec = 0x3e8;
            this._MaxSleepMsec = 0x1d4c0;
            this._MinSleepMsec = 0x3e8;
            this._SleepStep = 0x2710;
            this._MaxSleepMsec = MaxSleepMsec;
            this._MinSleepMsec = MinSleepMsec;
            if (this._MaxSleepMsec <= this._MinSleepMsec)
            {
                this._MaxSleepMsec = this._MinSleepMsec + 0x493e0;
            }
        }

        public RateControlHelper(int SleepStep, int MaxSleepMsec, int MinSleepMsec)
        {
            this._SleepMsec = 0x3e8;
            this._MaxSleepMsec = 0x1d4c0;
            this._MinSleepMsec = 0x3e8;
            this._SleepStep = 0x2710;
            this._SleepStep = SleepStep;
            this._MaxSleepMsec = MaxSleepMsec;
            this._MinSleepMsec = MinSleepMsec;
            if (this._MaxSleepMsec <= this._MinSleepMsec)
            {
                this._MaxSleepMsec = this._MinSleepMsec + 0x493e0;
            }
        }

        private void Corrector()
        {
            if (this._SleepMsec > this._MaxSleepMsec)
            {
                this._SleepMsec = this._MaxSleepMsec;
            }
            else if (this._SleepMsec < this._MinSleepMsec)
            {
                this._SleepMsec = this._MinSleepMsec;
            }
        }

        public virtual int Error()
        {
            this._SleepMsec += this._SleepStep;
            this.Corrector();
            return this._SleepMsec;
        }

        public virtual int None()
        {
            this._SleepMsec = this._MaxSleepMsec;
            return this._SleepMsec;
        }

        public virtual int Successful()
        {
            this._SleepMsec = this._MinSleepMsec;
            return this._SleepMsec;
        }

        // Properties
        public int SleepMsec
        {
            get
            {
                return this._SleepMsec;
            }
        }
    }

}
